package com.zzw.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Redis持久化配置类
 * 用于生成redis.conf配置文件并控制Redis持久化行为
 */
@Component
@Configuration
public class RedisPersistenceConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(RedisPersistenceConfig.class);
    
    // RDB配置参数
    @Value("${redis.persistence.rdb.enabled:true}")
    private boolean rdbEnabled;
    
    @Value("${redis.persistence.rdb.file-name:dump.rdb}")
    private String rdbFileName;
    
    @Value("${redis.persistence.rdb.directory:/data}")
    private String rdbDirectory;
    
    @Value("${redis.persistence.rdb.save-settings:900 1 300 10 60 10000}")
    private String rdbSaveSettings;
    
    // AOF配置参数
    @Value("${redis.persistence.aof.enabled:true}")
    private boolean aofEnabled;
    
    @Value("${redis.persistence.aof.file-name:appendonly.aof}")
    private String aofFileName;
    
    @Value("${redis.persistence.aof.directory:/data}")
    private String aofDirectory;
    
    @Value("${redis.persistence.aof.sync-strategy:everysec}")
    private String aofSyncStrategy;
    
    @Value("${redis.persistence.aof.rewrite-enabled:true}")
    private boolean aofRewriteEnabled;
    
    @Value("${redis.persistence.aof.rewrite-size-threshold:100}")
    private int aofRewriteSizeThreshold;
    
    @Value("${redis.persistence.aof.rewrite-percentage:100}")
    private int aofRewritePercentage;
    
    // 配置文件的临时路径
    @Value("${redis.config.path:./redis-config}")
    private String configPath;
    
    /**
     * 初始化方法，生成自定义的redis.conf文件
     */
    @PostConstruct
    public void init() {
        generateRedisConfig();
    }
    
    /**
     * 生成Redis配置文件
     */
    private void generateRedisConfig() {
        try {
            // 创建配置目录
            Path configDir = Paths.get(configPath);
            if (!Files.exists(configDir)) {
                Files.createDirectories(configDir);
            }
            
            // 配置文件路径
            File configFile = new File(configPath + "/redis.conf");
            
            // 创建文件并写入配置
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(configFile))) {
                // 添加基本配置
                writer.write("# Redis配置文件 - 自动生成\n\n");
                
                // 目录配置
                writer.write("# 基本配置\n");
                writer.write("dir " + rdbDirectory + "\n\n");
                
                // RDB配置
                writer.write("# RDB持久化配置\n");
                if (rdbEnabled) {
                    writer.write("# 启用RDB持久化\n");
                    writer.write("dbfilename " + rdbFileName + "\n");
                    
                    // 保存策略，格式为"save <seconds> <changes>"
                    String[] saveSettings = rdbSaveSettings.split(" ");
                    for (int i = 0; i < saveSettings.length; i += 2) {
                        if (i + 1 < saveSettings.length) {
                            writer.write("save " + saveSettings[i] + " " + saveSettings[i + 1] + "\n");
                        }
                    }
                } else {
                    writer.write("# 禁用RDB持久化\n");
                    writer.write("save \"\"  # 禁用RDB\n");
                }
                writer.write("\n");
                
                // AOF配置
                writer.write("# AOF持久化配置\n");
                writer.write("appendonly " + (aofEnabled ? "yes" : "no") + "\n");
                
                if (aofEnabled) {
                    writer.write("appendfilename \"" + aofFileName + "\"\n");
                    writer.write("appendfsync " + aofSyncStrategy + "\n");
                    
                    // AOF重写配置
                    writer.write("auto-aof-rewrite-percentage " + aofRewritePercentage + "\n");
                    writer.write("auto-aof-rewrite-min-size " + aofRewriteSizeThreshold + "mb\n");
                }
                
                writer.write("\n# 其他配置\n");
                writer.write("stop-writes-on-bgsave-error yes\n");
                writer.write("rdbcompression yes\n");
                writer.write("rdbchecksum yes\n");
                
                logger.info("成功生成Redis配置文件: " + configFile.getAbsolutePath());
            }
        } catch (IOException e) {
            logger.error("生成Redis配置文件失败", e);
        }
    }
    
    /**
     * 获取Redis配置文件路径
     */
    @Bean
    public String redisConfigFilePath() {
        return configPath + "/redis.conf";
    }
    
    /**
     * 更新持久化配置并重新生成配置文件
     * @param rdbEnabled RDB是否启用
     * @param aofEnabled AOF是否启用
     */
    public void updatePersistenceConfig(boolean rdbEnabled, boolean aofEnabled) {
        this.rdbEnabled = rdbEnabled;
        this.aofEnabled = aofEnabled;
        generateRedisConfig();
        logger.info("已更新Redis持久化配置: RDB={}, AOF={}", rdbEnabled, aofEnabled);
    }
} 